import { useEffect, useRef } from "react";
import {
  ProForm,
  ProFormText,
  ProFormTextArea,
  PageContainer,
  ProFormInstance,
} from "@ant-design/pro-components";
import styles from "./index.module.less";
import { Col, Form, Row, message } from "antd";
import OSSImageUpload from "@/components/OSSImageUpload";
import { useUserContext } from "@/hooks/userHooks";
import { useMutation } from "@apollo/client";
import { UPDATE_USER_INFO } from "@/graphql/user";

/**
 *我的页面
 */
const My = () => {
  const formRef = useRef<ProFormInstance>();
  const { store, setStore } = useUserContext();
  console.log("store", store);
  const [updateUserInfo] = useMutation(UPDATE_USER_INFO);
  useEffect(() => {
    if (!store.tel) return;
    formRef.current?.setFieldsValue({
      tel: store.tel,
      name: store.name,
      desc: store.desc,
      avatar: [
        {
          url: store.avatar,
        },
      ],
    });
  }, [store]);
  return (
    <PageContainer className={styles.container}>
      <ProForm
        formRef={formRef}
        layout="horizontal"
        submitter={{
          resetButtonProps: {
            style: {
              display: "none",
            },
          },
        }}
        onFinish={async (values) => {
          console.log("values", values);
          const res = await updateUserInfo({
            variables: {
              id: store.id,
              params: {
                name: values.name,
                desc: values.desc,
                avatar: values.avatar?.[0]?.url || "",
              },
            },
          });
          if (res.data?.updateUserInfo.code === 200) {
            setStore({
              ...store,
              name: values.name,
              desc: values.desc,
              avatar: values.avatar?.[0]?.url || "",
            });
            message.success("更新成功");
            return;
          } else {
            message.error(res.data?.updateUserInfo.message);
          }
        }}
      >
        <Row gutter={20}>
          <Col>
            <ProFormText
              name="tel"
              label="手机号"
              tooltip="不能修改"
              disabled
            />
            <ProFormText name="name" label="昵称" placeholder="请输入昵称" />
            <ProFormTextArea
              name="desc"
              label="简介"
              placeholder="请输入简介"
            />
          </Col>
          <Col>
            <Form.Item label="头像" name="avatar">
              <OSSImageUpload label="替换头像" />
            </Form.Item>
          </Col>
        </Row>
      </ProForm>
    </PageContainer>
  );
};

export default My;
